import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  WebSocketServer,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { NotificationService } from './notification.service';

@WebSocketGateway(3001, { cors: true })
export class NotificationGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  constructor(private readonly notificationService: NotificationService) {}

  @WebSocketServer() server: Server;

  afterInit(server: Server) {
    console.log('WebSocket 服务器已初始化');
  }

  handleConnection(client: Socket) {
    console.log(`客户端连接成功: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`客户端断开连接: ${client.id}`);
  }

  // 处理客户端消息
  @SubscribeMessage('sendMessage')
  handleMessage(@MessageBody() data: string): void {
    console.log(`收到消息: ${data}`);
    this.server.emit('receiveMessage', `服务器收到消息: ${data}`);
  }

  // 服务器主动向所有客户端推送消息
  sendToAllClients(message: string, userIds: number[]) {
    this.server.emit('receiveMessage', message);
    return this.notificationService.sendEnterpriseNotification(
      message,
      userIds,
    );
  }
}
